<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <title-name v-if="!$route.meta.isDetail" :title="processName+'-'+taskName"></title-name>
        <a-card v-if="!$route.meta.isDetail" :body-style="{ padding: '24px 32px' }" :bordered="false">
            <title-name title="节点信息"></title-name>
            <a-descriptions title="">
                <a-descriptions-item label="当前节点">
                    {{taskName}}
                </a-descriptions-item>
                <a-descriptions-item label="审批人">
                    {{currentUser.name}}
                </a-descriptions-item>
                <a-descriptions-item label="审批时间">
                    {{currentTime}}
                </a-descriptions-item>
            </a-descriptions>

            <title-name title="审批意见"></title-name>
            <a-form :form="form" ref="form1" layout="vertical">
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item>
                            <BaseInput v-model="opinions" style="width:100%" placeholder="请填写审批意见" type="textarea"></BaseInput>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24" class="overfloat">
                    <a-col>
                      <Consultation
                        :proc-inst-id="procInstId"
                        :is-show-btn="$route.query.isMonitoring ? ($route.query.monitoringType==='process' ? true: false): true"
                        :task-name="taskName"
                        :sub-approver-list.sync="subApproverList"
                      >
                        <template slot="approverButton">
                          <a-button type="primary" style="margin-right: 20px;" @click="handelUnApproval">审批不通过</a-button>
                          <a-button type="primary" @click="handelApproval">审批通过</a-button>
                        </template>
                      </Consultation>
                    </a-col>
                </a-row>
            </a-form>


            <title-name title="审批流程信息"></title-name>
            <div class="btns-wrapp mb20">
                <a-button type="primary" @click="visibleState.auditProcess = true">审批流程图</a-button>
            </div>

            <a-spin tip="流程信息加载中..." :spinning="flowRequesting">
                <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
                    <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                </a-table>
            </a-spin>
        </a-card>

        <a-card :bordered="false" >
            <title-name title="项目人员调整信息"></title-name>
            <a-form-model ref="ruleForm" :model="forms"
                          :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                          :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
                <a-row>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="分公司名称">
                            <BaseInput v-model="form.branchName" disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="项目名称">
                            <BaseInput v-model="form.projectName" disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调整岗位名称">
                            <BaseInput v-model="form.jobName"  disabled/>
                        </a-form-model-item>
                    </a-col>
                </a-row>


                <a-row   v-if="statusCode == 2">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调整类型">
                            <BaseInput v-model="form.statusName"  disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调入人员名称">
                            <BaseInput v-model="form.newEmployeeName" disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调入人员员工编号">
                            <BaseInput v-model="form.newEmployeeNum"  disabled/>
                        </a-form-model-item>
                    </a-col>
                </a-row>



                <a-row   v-if="statusCode ==1">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调整类型">
                            <BaseInput v-model="form.statusName"  disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="被移除人员">
                            <BaseInput v-model="form.oldEmployeeName"  disabled/>
                        </a-form-model-item>
                    </a-col>
                </a-row>



                <a-row v-if="statusCode == 0">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调整类型">
                            <BaseInput v-model="form.statusName" disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="被更换人员">
                            <BaseInput v-model="form.oldEmployeeName" disabled/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调入人员名称">
                            <BaseInput v-model="form.newEmployeeName" disabled/>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row v-if="statusCode == 1">
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="调入人员员工编号">
                            <BaseInput v-model="form.newEmployeeNum" disabled/>
                        </a-form-model-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :md="24" :sm="24">
                        <a-table :columns="columnsInfo" :data-source="dataSources" bordered :pagination="false"></a-table>
                    </a-col>
                </a-row>


            </a-form-model>
        </a-card>
        <div v-if="!isConsultation" class="btn_box page-btn-right-top">
          <a-button @click="window.close()">关闭</a-button>
        </div>
        <ApprovalDetails
                :title="'审批流程信息'"
                :businessId="this.id"
                :visible="visibleState.auditProcess"
                @cancel="visibleState.auditProcess = false"
                @confirm="visibleState.auditProcess = false"
        />

    </base-breadcrumb>
</template>

<script>
  import ApprovalDetails from '@/components/approvalDetails'
  import FooterToolBar from '@/components/FooterToolbar'
  import { getDesignType, getProjectsDel, getDepartConfig, getProjectTypes } from '@/api/project/projects'
  import { getDetailInAudit } from '@/api/project/adjust'
  import {getProcessNodeList,completeTask} from '@/api/process'
  import { getJobEmployee } from '@/api/project/projects'
  import { notifyParentWindow } from '@/utils/util.js'
  import {getOrgEmployeesListBy} from '@/api/commons'
  import Consultation from '@/views/matters/approval/components/consultation'
  import moment from 'moment'
  import Vue from 'vue'
  import { postChangeLog } from '@/mixin/mixin'

  const columnApprove = [
    {
      title: '序号',
      width:80,
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '审批人',
      dataIndex: 'userName',
    },
    {
      title: '审批时间',
      dataIndex: 'createTime',
    },
    {
      title: '节点名称',
      dataIndex: 'taskName',
    },
    {
      title: '滞留时间',
      dataIndex: 'durationInMillis',
    },
    {
      title: '审批意见',
      dataIndex: 'formData.opinions',
    }
  ]
  const columnsInfo = [
    {
      title: '所在单位',
      dataIndex: 'branch',
    },
    {
      title: '所在部门',
      dataIndex: 'projectName',
    },
    {
      title: '当前岗位',
      dataIndex: 'jobName',
    }
  ]
  export default {
    mixins: [postChangeLog],
    name: 'StandardList',
    components: {
      FooterToolBar,
      ApprovalDetails,
      Consultation
    },
    props: {
      text: String,
      // 是否作为审批详情
      isAudit: {
        type: Boolean,
        default: false
      },
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        window: window,
        visibleState: {
          auditProcess: false
        },
        opinions:'',

        spinning:false,
        columnApprove,
        approveInfos:[], // 审批流程信息
        columnsInfo,

        dataSource:[],
        dataSources:[],

        id:'',
        statusCode:2 ,  // 0：替换，1：移除，2：新增

        visible:false,
        forms:{},

        form:{
          createTime:this.getNowTime()
        },

        procInstId:'', //当前流程实例ID
        taskId:'', //当前流程节点ID
        processName:'',//流程名称
        taskName:'',//当前流程节点名称
        taskDefKey:'',//任务标识
        currentTime:'',//当前审批时间
        currentUser:'',//当前审批人
        flowRequesting: false,
        // 下级审批人
        subApproverList: []
      }
    },
    created() {
      this.id = this.$route.query.businessId
      if(!this.id){
        this.$error({content:'无指定调整数据，将自动关闭'})
        setTimeout(()=>{
          window.close();
        },1500)
        return
      }
      this.procInstId = this.$route.query.procInstId
      this.taskName = decodeURIComponent(this.$route.query.name)
      this.processName = decodeURIComponent(this.$route.query.processName)
      this.taskId = this.$route.query.taskId
      this.taskDefKey = this.$route.query.taskDefKey
      this.currentTime = moment().format('yyyy-MM-DD HH:mm')
      this.currentUser = Vue.getAcloudProvider().getUserInfo()
      //获取流程节点执行情况(非详情查看的情况下)
      if(!this.$route.meta.isDetail) {
        document.title=this.processName+'-'+this.taskName;
        this.getProcessNodes()
      }
      this.getAdjustListDels()
    },
    computed: {
    },
    methods: {
      getAdjustListDels(){
        getDetailInAudit({id: this.id}).then(res=>{
          if(res.code == 200){
            this.form = res.data
            this.statusCode = res.data.statusCode
            if(res.data.newUserId){
              getJobEmployee({ids:[res.data.newUserId],projectAuditStatus:2,employeeStatus:0}).then(response=>{
                this.dataSources = response.data
              })
            }

          }

        })
      },
      getProcessNodes(){
        this.flowRequesting = true
        getProcessNodeList({procInstId:this.procInstId,pageNo:1,pageSize:100}).then(res=>{
          if(res.code===200){
            const data =res.data
            const userIds = data.map(d=>{
              if(d.formData){
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({userIds}).then(employees=>{
              this.flowRequesting = false
              res.data.forEach(r=>{
                employees.data.some(e=>{
                  if(e.userId===r.assignee){
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data
            })
          }
        }).catch(()=>{
          this.flowRequesting = false
        })
      },
      /**
       * @description: 组装下级审批人数据
       * @param {array} subApproverList 下级审批人表格数据
       * @return {object} 下级审批人数据
       */
      createApproverList(subApproverList) {
        const subordinateApproverList = {}
        subApproverList.forEach((item) => {
          if (item?.approver && item.approver.length > 0) {
            subordinateApproverList[item.taskInfo.id] = {
              assgins: item.approver?.map((el) => el.key).join(','),
              assignTypeEnum: 2
            }
          }
        })
        return subordinateApproverList
      },
      submit(reject){
        const data = {
          "formData": {
            opinions:this.opinions,
            reject
          },
          "procInstId": this.procInstId,
          "taskId": this.taskId,
          "userId": this.currentUser.id
        }
        if(reject){
          data["variables"]={reject:true}
        }
        return completeTask(data).then(res=>{
          if(res.status===200){
            // this.$success({content:'审批提交成功，即将自动关闭当前窗口',onOk() {window.close()}})
            // setTimeout(()=>{
              window.close()
            // },2000)
          }else{
            this.$error({content:'审批提交失败，请稍后重试'})
          }
          return res
        }).catch(err=>{
          return err
        })
      },
      handelUnApproval(){  // 审批不通过
        const _this = this
        if(!_this.opinions){
          _this.$warning({content:'请填写审批意见'})
          return;
        }
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批不通过？',
          okType: 'danger',
          onOk() {
            return new Promise((resolve, reject) => {
              _this.submit(true).then(()=>{
                notifyParentWindow() // 通知父窗口
                resolve();
                confirmWin.destroy();
              }).catch(()=>reject)
            }).catch(() => this.$error({content:'审批提交失败，请稍后重试'}));
          },
          onCancel() {
          },
        });
      },
      handelApproval(){    // 审批通过
        const _this = this
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批通过？',
          okType: 'danger',
          onOk() {
            return new Promise((resolve, reject) => {
              _this.submit(false, _this.createApproverList(_this.subApproverList)).then(()=>{
                _this.handleGetPostsChangeLog() //获取一周内岗位变更数量
                notifyParentWindow() // 通知父窗口
                resolve();confirmWin.destroy();}).catch(()=>reject)
            }).catch(() => this.$error({content:'审批提交失败，请稍后重试'}));
          },
          onCancel() {
          },
        });
      }
    }
  }
</script>

<style lang="less" scoped>
</style>

